package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.injector.methods.SelectById;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDTO;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {


    /**
     * 自媒体用户登录
     * @param wmUserDTO
     * @return
     */
    @Override
    public ResponseResult login(WmUserDTO wmUserDTO) {
        //检查参数
        String password = wmUserDTO.getPassword();
        String name = wmUserDTO.getName();
        if (StringUtils.isBlank(password) || StringUtils.isBlank(name)){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"用户名或密码不能为空");
        }
        //根据用户名查询数据
        WmUser wmUser = getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, name));
        if (wmUser == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该用户还没注册");
        }

        //判断用户状态啊
        if (wmUser.getStatus().intValue() != 9){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"用户状态异常,请联系管理员.");
        }

        //获取加密密码
        String newPassword = DigestUtils.md5DigestAsHex((password+wmUser.getSalt()).getBytes(StandardCharsets.UTF_8));
        //判断密码
        if (!newPassword.equals(wmUser.getPassword())){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
        }

        //表示用户登录没问题  办法token
        Map<String,Object> map = new HashMap<>();
        map.put("token", AppJwtUtil.getToken(Long.valueOf(wmUser.getId())));
        WmUserVO wmUserVO = new WmUserVO();
        BeanUtils.copyProperties(wmUser,wmUserVO);
        map.put("user",wmUserVO);

        return ResponseResult.okResult(map);
    }




}




